/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lilanz.facepass.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lilanz.facepass.controller.push.dto.Message;
import com.lilanz.facepass.entity.exception.MyException;
import org.springframework.util.DigestUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


public class ToolUtil {

    //字母排序，第一个字母相同，按第二个。。以此类推
    public static String getKey(Map<String, String> map) {
        String[] strings = map.keySet().toArray(new String[0]);
//        Arrays.sort(strings);//java自带的算法排序
        sort(strings);//自己写的算法  两种均可以

        StringBuilder sb = new StringBuilder();
        for (String string : strings) {
            sb.append(string).append("=").append(map.get(string)).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);//删除最后一个&字符
        return DigestUtils.md5DigestAsHex(sb.toString().getBytes());//MD5加密
    }


    //字母排序，第一个字母相同，按第二个。。以此类推
    public static void sort(String[] strings) {
        for (int i = 0; i < strings.length; i++) {
            for (int j = i + 1; j < strings.length; j++) {
                sort(strings, i, j, 0);
            }
        }
    }

    private static void sort(String[] strings, int i, int j, int count) {
        int frontOne = strings[i].charAt(count);//前首字母
        int backOne = strings[j].charAt(count);//后首字母
        if (frontOne > backOne) {
            String temp = strings[j];
            strings[j] = strings[i];
            strings[i] = temp;
        } else if (frontOne == backOne) {//比较除第一个字母之后的排序
            int iLength = strings[i].length();
            int jLength = strings[j].length();
            if (iLength == (count + 1) || jLength == (count + 1)) {
                if (iLength > jLength) {
                    String temp = strings[j];
                    strings[j] = strings[i];
                    strings[i] = temp;
                }
            } else {
                sort(strings, i, j, count + 1);
            }
        }
    }


    public static void main(String args[]) {
        try {
//            Message message = new Message();
//            message.setAge(12);
//            message.setMsgid("xiaoxiid");
            Map<String,Object> map=new HashMap<>();
            map.put("type", 1);

            System.out.println(JSON.toJSONString(map));
            // 创建url资源
            URL url = new URL("http://127.0.0.1:80/push/getMessage");
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (JSON.toJSONString(map).getBytes());
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");


            // 开始连接请求
            conn.connect();
            OutputStream out = conn.getOutputStream();
            // 写入请求的字符串
            out.write(JSON.toJSONString(map).getBytes());
            out.flush();
            out.close();

            System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (conn.getResponseCode() == 200) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in = conn.getInputStream();
                String a = null;
                try {
                    byte[] data1 = new byte[in.available()];
                    in.read(data1);
                    // 转成字符串
                    a = new String(data1);
                    System.out.println(a);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } finally {
                    in.close();
                }

            } else {
                System.out.println("no++");
            }

        } catch (Exception e) {

        }

    }


    public static Map<String, Object> getNamValMap(Object obj, boolean isSort) {
        Map<String, Object> map = null;
        if (isSort) {
            map = new TreeMap<String, Object>();
        } else {
            map = new HashMap<String, Object>();
        }
        Field[] fieldArr = obj.getClass().getDeclaredFields();
        try {
            for (Field field : fieldArr) {
                field.setAccessible(true);
                if (field.get(obj) != null && !"".equals(field.get(obj).toString())) {
                    map.put(field.getName(), field.get(obj).toString());
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new MyException("原因为: " + e.getMessage());
        }

        return map;
    }

//    private static void main(String[] args) {
//        long l = System.currentTimeMillis();
//        Map<String, String> map = new HashMap<>();
//        map.put("phoneNo", "13055621836");
//        map.put("password", "pass");
//        map.put("vi", "00400300200");
//        System.out.println(getKey(map));
//        long l1 = System.currentTimeMillis();
//        System.out.println(l1 - l);
//    }

}


